<?php
/*
 +----------------------------------------------------------------------
 + Title        : Validator 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2020/5/6 11:15
 + Last-time    : 2020/5/6 11:15+ 86187
 + Desc         : Validator
 +----------------------------------------------------------------------
*/


namespace myAnnotation\rules;


use think\exception\ValidateException;
use think\Validate;

class ValidatorRule {
    function run(\myAnnotation\Annotation\Validator $validator){
        /**@var $validate \think\validate */
        $validate = app($validator->class);
        $validateErrorMsgCallback = config('?system.annotation.validate.callback') ? config('system.annotation.validate.callback') : [];
        if (!$validate instanceof Validate) {
            throw new \Exception('class ' . $validator->class . ' is not a thinkphp validate class');
        }
        if ($validator->batch) {
            $validate->batch();
        }
        if ($validator->scene) {
            $validate->scene($validator->scene);
        }
        if (!$validate->check(app('request')->param())) {
            if ($validator->throw) {
                throw new ValidateException($validate->getError());
            } else {
                if ($validateErrorMsgCallback && $validateErrorMsgCallback instanceof \Closure) {
                    call_user_func($validateErrorMsgCallback, $validate->getError());
                } else {
                    exit($this->formatErrorMsg($validate->getError()));
                }
            }
        }
    }

    /**
     * 格式化错误信息
     *
     * @param string $msg
     *
     * @return false|string
     */
    protected function formatErrorMsg($msg = '') {
        return json_encode([
                               'code' => 422,
                               'data' => '',
                               'msg'  => $msg,
                               'time' => request()->time()
                           ]);
    }
}